package com.webserver.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 请求对象
 * 该类的每一个实例表示客户端发过来的一个请求。
 * 每个请求有三部分构成
 *1：请求行
 * 2：消息头
 * 3：消息正文
 */

public class HttpServletRequest {
    private Socket socket;
    //请求行相关信息
    private String method;
    private String uri;
    private String protocol;
    private String requestURI;
    private String queryString;
    private Map<String,String> parameters = new HashMap<>();
    private byte[] contentData;
    //消息头相关信息
    private Map<String,String> headers = new HashMap<>();

    public HttpServletRequest(Socket socket) throws IOException, EmptyRequestException {
        this.socket = socket;
        //1：解析请求行
        parseRequestLine();
        //2:解析消息头
        parseHeaders();
        //3:解析消息正文
        parseContent();


    }

    private void parseRequestLine() throws IOException, EmptyRequestException {
        String line = readline();
        if (line.isEmpty()){
            throw new EmptyRequestException();
        }
        System.out.println("请求行:"+line);
        String[] data = line.split("\\s");
        method = data[0];
        uri = data[1];
        parseUri();//进一步解析Uri
        protocol = data[2];
        System.out.println("method:"+method);
        System.out.println("uri:"+uri);
        System.out.println("protocol:"+protocol);
    }

    /**
     * 进一步解析Uri
     */
    private void parseUri(){
         /*
            uri有两种情况:
            1:含参数的
              例如:
                  |请求部分 |?|                   参数部分                          |
              uri:/myweb/reg?username=zhangsan&password=123456&nickname=asan&age=22
              将uri按照"?"拆分为请求部分与参数部分,将请求部分赋值给requestURI
              将参数部分赋值给queryString
              再将参数部分进行拆分,首先按照"&"拆分出每一组参数,每组参数再按照
              "="拆分为参数名与参数值,并将参数名作为key,参数值作为value保存到
              parameters这个Map中




            2:不含参数的
              例如:
              uri:/root/404.png
              直接将uri的值赋值给requestURI即可
         */
        String[] data = uri.split("\\?");
        requestURI = data[0];
        if (data.length>1){
            queryString = data[1];
           parseParameters(queryString);
        }



        //自己写的
//        if (uri.contains("?")){
//            String[] data = uri.split("\\?");
//            requestURI = data[0];
//            queryString = data[1];
//            String[] a = queryString.split("&");
//            for (String b:a){
//                String[] c = b.split("=");
//                String key = c[0];
//                if (c.length==1){
//                    String value = null;
//                    parameters.put(key,value);
//                }else {
//                    String value = c[1];
//                    parameters.put(key,value);
//                }
//            }
//
//        }else {
//            requestURI =uri;
//        }
        System.out.println("requestURI:"+requestURI);
        System.out.println("queryString:"+queryString);
        System.out.println("parameters:"+parameters);

    }
    /*
    拆分参数初始化
     */
    private void parseParameters(String line){
        String[] paraArr = line.split("&");
        for (String para :paraArr){
            String[] paras = para.split("=");
            if (paras.length>1){
                parameters.put(paras[0],paras[1]);
            }else {
                parameters.put(paras[0],null);
            }
        }
    }
    private void parseHeaders() throws IOException {
        while (true) {
          String  line = readline();
            if (line.isEmpty()){
                break;
            }
            System.out.println("消息头：" + line);
           String[] data =line.split(":\\s");
            headers.put(data[0],data[1]);
        }
        System.out.println("headers:"+headers);
    }
    private void parseContent() throws IOException {
        //获取消息头
        if (headers.containsKey("Content-Length")){
            int len = Integer.parseInt(headers.get("Content-Length"));
            contentData = new byte[len];
            InputStream in = socket.getInputStream();
            in.read(contentData);//一次性快读所有正文数据

            if (headers.containsKey("Content-Type")){
                String contentType = headers.get("Content-Type");
                if ("application/x-www-form-urlencoded".equals(contentType)){
                    String line = new String(contentData,"ISO8859-1");
                    System.out.println("正文内容:"+line);
                    parseParameters(line);
                }
            }



        }
    }

    private String readline() throws IOException {
        InputStream in = socket.getInputStream();
        StringBuilder builder = new StringBuilder();
        char cur = 'a';
        char pre = 'a';
        int d;
        while ((d = in.read())!=-1){
            cur = (char) d;
            if (pre==13 && cur==10){
                break;
            }
            builder.append(cur);
            pre = cur;
        }
        return  builder.toString().trim();
    }

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }

    public String getHeader(String name){
        return headers.get(name);
    }

    public String getRequestURI() {
        return requestURI;
    }

    public String getQueryString() {
        return queryString;
    }
    public String getParameter(String name){
        String value = parameters.get(name);
        if (value!=null){
            try {
                value = URLDecoder.decode(value,"UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return value;

    }
}
